import { npmAudit } from "./npmAudit.js";
import { currentAudit } from "./currentAudit.js";
import { normalizeAuditResult } from "./normalizeAuditResult.js";

export async function audit(workDir, packageJson) {
    // 1. 获取npm audit结果
    const npmAuditResult = await npmAudit(workDir);

    // 2. 获取格式化后的npm audit结果
    const normalizedNpmAuditResult = normalizeAuditResult(npmAuditResult);

    // 3. 获取当前工程审计结果,就是包本身
    const currentAuditResult = await currentAudit(packageJson.name, packageJson.version);

    // 4. 合并npm audit结果和当前工程审计结果
    if (currentAuditResult) {
        normalizedNpmAuditResult.vulnerabilities[currentAuditResult.severity].unshift(currentAuditResult)

    }

    // 5. 添加汇总信息
    normalizedNpmAuditResult.summary = {
        total: Object.values(normalizedNpmAuditResult.vulnerabilities).reduce(
            (sum, arr) => sum + arr.length,
            0
        ),
        critical: normalizedNpmAuditResult.vulnerabilities.critical.length,
        high: normalizedNpmAuditResult.vulnerabilities.high.length,
        moderate: normalizedNpmAuditResult.vulnerabilities.moderate.length,
        low: normalizedNpmAuditResult.vulnerabilities.low.length,
        // info: normalizedNpmAuditResult.vulnerabilities.info.length,
    }

    return normalizedNpmAuditResult;

}